package com.xz.optometry.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.xz.common.annotation.DataScope;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.service.ISysAccessoryService;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.optometry.domain.OptometryItem;
import com.xz.optometry.service.IOptometryItemService;
import com.xz.optometry.vo.OptometryExportVo;
import com.xz.optometry.vo.OptometryInfoVo;
import com.xz.optometry.vo.OptometryVo;
import com.xz.supplier.dto.SupplierAccessoryDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.optometry.mapper.OptometryMapper;
import com.xz.optometry.domain.Optometry;
import com.xz.optometry.service.IOptometryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 验光配镜Service业务层处理
 *
 * @author xz
 * @date 2024-01-31
 */
@Service
public class OptometryServiceImpl extends ServiceImpl<OptometryMapper, Optometry> implements IOptometryService {
    @Autowired
    private OptometryMapper optometryMapper;
    @Autowired
    private ISysAccessoryService iSysAccessoryService;
    @Autowired
    private IOptometryItemService iOptometryItemService;

    /**
     * 查询验光配镜
     *
     * @param id 验光配镜主键
     * @return 验光配镜
     */
    @Override
    public OptometryInfoVo selectOptometryById(Long id) {
        OptometryInfoVo optometryInfoVo = optometryMapper.selectOptometryById(id);
        if(Objects.nonNull(optometryInfoVo)){
            List<String> stringList = iSysAccessoryService.selectSupplierAccessoryUrlList(id.toString(), 2);
            optometryInfoVo.setUrlList(stringList);
        }
        return optometryInfoVo;
    }

    /**
     * 查询验光配镜列表
     *
     * @param optometry 验光配镜
     * @return 验光配镜
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<OptometryVo> selectOptometryList(Optometry optometry) {
        return optometryMapper.selectOptometryList(optometry);
    }

    /**
     * 查询验光配镜列表(导出)
     *
     * @param optometry 验光配镜
     * @return 验光配镜
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<OptometryExportVo> selectOptometryListForExport(Optometry optometry) {
      return optometryMapper.selectOptometryListForExport(optometry);
    }

    @Override
    public List<OptometryVo> selectByPatientId(Optometry optometry){
        return optometryMapper.selectByPatientId(optometry);
    }

    /**
     * 新增验光配镜
     *
     * @param optometry 验光配镜
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertOptometry(Optometry optometry) {
        List<OptometryItem> optometryItemList = optometry.getOptometryItemList();
        if(CollectionUtils.isEmpty(optometryItemList)){
            return AjaxResult.error("配镜明细不能为空");
        }
        optometry.setStatus(1);
        optometry.setOptometryNo(RedisCode.getCode("YG"));
        optometry.setCreateTime(DateUtils.getNowDate());
        optometry.setCreateBy(SecurityUtils.getUserId());
        optometry.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        dataOptometry(optometry,optometryItemList);
        int insertOptometry = optometryMapper.insertOptometry(optometry);
        if(insertOptometry>0){
            //插入配镜明细
            optometryItemList.stream().forEach(i->i.setOptometryId(optometry.getId()));
            iOptometryItemService.saveBatch(optometryItemList);
            if(!CollectionUtils.isEmpty(optometry.getUrlList())){
                iSysAccessoryService.insertStringUrlList(optometry.getUrlList(),optometry.getId().toString(),2,1);

            }
        }
        return insertOptometry>0? AjaxResult.success("新增成功",optometry):AjaxResult.error("新增失败",optometry);
    }
    public void dataOptometry(Optometry optometry,List<OptometryItem> optometryItemList){
        List<OptometryItem> itemList = optometryItemList.stream().filter(i -> i.getOptometryType() == 2).collect(Collectors.toList());
        StringBuilder prescriptionVisualDistanc_OD= new StringBuilder("OD：");//处方信息-视远
        StringBuilder prescriptionVisualDistanc_OS= new StringBuilder("OS：");//处方信息-视远
        StringBuilder prescriptionRead_OD= new StringBuilder("OD：");//处方信息-阅读
        StringBuilder prescriptionRead_OS= new StringBuilder("OS：");//处方信息-阅读
        for(OptometryItem item:itemList){
            if(item.getOptometryUse()==1){
                if(item.getEyeCategory()==1) {
                    if (StringUtils.isNotEmpty(item.getSphericalLens())) {
                        prescriptionVisualDistanc_OD.append(item.getSphericalLens());
                    }
                    if (StringUtils.isNotEmpty(item.getNylindricalMirror())) {
                        prescriptionVisualDistanc_OD.append("/").append(item.getNylindricalMirror());
                    }
                    if (StringUtils.isNotEmpty(item.getNxialDirection())) {
                        prescriptionVisualDistanc_OD.append("X").append(item.getNxialDirection());
                    }
                    if (StringUtils.isNotEmpty(item.getTriplePrism())) {
                        prescriptionVisualDistanc_OD.append("/△").append(item.getTriplePrism());
                    }
                    if (StringUtils.isNotEmpty(item.getBasad())) {
                        prescriptionVisualDistanc_OD.append(" ").append(item.getBasad());
                    }
                }
                if(item.getEyeCategory()==2) {
                    if (StringUtils.isNotEmpty(item.getSphericalLens())) {
                        prescriptionVisualDistanc_OS.append(item.getSphericalLens());
                    }
                    if (StringUtils.isNotEmpty(item.getNylindricalMirror())) {
                        prescriptionVisualDistanc_OS.append("/").append(item.getNylindricalMirror());
                    }
                    if (StringUtils.isNotEmpty(item.getNxialDirection())) {
                        prescriptionVisualDistanc_OS.append("X").append(item.getNxialDirection());
                    }
                    if (StringUtils.isNotEmpty(item.getTriplePrism())) {
                        prescriptionVisualDistanc_OS.append("/△").append(item.getTriplePrism());
                    }
                    if (StringUtils.isNotEmpty(item.getBasad())) {
                        prescriptionVisualDistanc_OS.append(" ").append(item.getBasad());
                    }
                }
            }else{
                if(item.getEyeCategory()==1) {
                    if (StringUtils.isNotEmpty(item.getSphericalLens())) {
                        prescriptionRead_OD.append(item.getSphericalLens());
                    }
                    if (StringUtils.isNotEmpty(item.getNylindricalMirror())) {
                        prescriptionRead_OD.append("/").append(item.getNylindricalMirror());
                    }
                    if (StringUtils.isNotEmpty(item.getNxialDirection())) {
                        prescriptionRead_OD.append("X").append(item.getNxialDirection());
                    }
                    if (StringUtils.isNotEmpty(item.getTriplePrism())) {
                        prescriptionRead_OD.append("/△").append(item.getTriplePrism());
                    }
                    if (StringUtils.isNotEmpty(item.getBasad())) {
                        prescriptionRead_OD.append(" ").append(item.getBasad());
                    }
                }
                if(item.getEyeCategory()==2) {
                    if (StringUtils.isNotEmpty(item.getSphericalLens())) {
                        prescriptionRead_OS.append(item.getSphericalLens());
                    }
                    if (StringUtils.isNotEmpty(item.getNylindricalMirror())) {
                        prescriptionRead_OS.append("/").append(item.getNylindricalMirror());
                    }
                    if (StringUtils.isNotEmpty(item.getNxialDirection())) {
                        prescriptionRead_OS.append("X").append(item.getNxialDirection());
                    }
                    if (StringUtils.isNotEmpty(item.getTriplePrism())) {
                        prescriptionRead_OS.append("/△").append(item.getTriplePrism());
                    }
                    if (StringUtils.isNotEmpty(item.getBasad())) {
                        prescriptionRead_OS.append(" ").append(item.getBasad());
                    }
                }
            }
        }
        optometry.setPrescriptionDistance(prescriptionVisualDistanc_OD.toString()+";"+prescriptionVisualDistanc_OS.toString()+";");
        optometry.setPrescriptionRead(prescriptionRead_OD.toString()+";"+prescriptionRead_OS.toString()+";");
    }

    /**
     * 修改验光配镜
     *
     * @param optometry 验光配镜
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateOptometry(Optometry optometry) {
        List<OptometryItem> optometryItemList = optometry.getOptometryItemList();
        if(CollectionUtils.isEmpty(optometryItemList)){
            return AjaxResult.error("配镜明细不能为空");
        }

        optometry.setUpdateTime(DateUtils.getNowDate());
        optometry.setUpdateBy(SecurityUtils.getUserId());
        dataOptometry(optometry,optometryItemList);
        int updateOptometry = optometryMapper.updateOptometry(optometry);
        if(updateOptometry>0){
            //删除配镜明细
            iOptometryItemService.deleteOptometryItemById(optometry.getId());
            //插入配镜明细
            optometryItemList.stream().forEach(i->i.setOptometryId(optometry.getId()));
            iOptometryItemService.saveBatch(optometryItemList);
            //删除历史附件
            iSysAccessoryService.deleteSysAccessoryByBizId(optometry.getId().toString(),2);
            if(!CollectionUtils.isEmpty(optometry.getUrlList())){
                iSysAccessoryService.insertStringUrlList(optometry.getUrlList(),optometry.getId().toString(),2,1);
            }
        }
        return updateOptometry>0? AjaxResult.success("修改成功",optometry):AjaxResult.error("修改失败",optometry);
    }

    /**
     * 批量删除验光配镜
     *
     * @param ids 需要删除的验光配镜主键
     * @return 结果
     */
    @Override
    public int deleteOptometryByIds(Long[] ids) {
        return optometryMapper.deleteOptometryByIds(ids);
    }

    /**
     * 删除验光配镜信息
     *
     * @param id 验光配镜主键
     * @return 结果
     */
    @Override
    public int updateOptometryById(Integer status,Long id) {
        return optometryMapper.updateOptometryById(status,id);
    }

    /**
     * 配镜处方
     * @param id
     * @return
     */
    @Override
    public OptometryInfoVo selectProcessOptometryById(Long id) {
        return optometryMapper.selectProcessOptometryById(id);
    }
}
